/**
 * Copyright (c) 2020 lizebang
 *
 * This software is released under the MIT License.
 * https://opensource.org/licenses/MIT
 */

package cmd

import (
	"os"
	"os/signal"
	"reflect"
	"syscall"

	"gitee.com/banggua/ggtsync/config"
	"gitee.com/banggua/ggtsync/handler"
)

var (
	signalCh = make(chan os.Signal)
)

func init() {
	signal.Notify(signalCh, syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL, syscall.SIGUSR1, syscall.SIGUSR2)
	go deamon()
}

func deamon() {
	for s := range signalCh {
		switch s {
		case syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL, syscall.SIGUSR2:
			handler.Shutdown()
		case syscall.SIGUSR1:
			oldProjects := config.GetProjects()
			err := config.Reload()
			if err != nil {
				continue
			}
			newProjects := config.GetProjects()

			for _, oldProject := range oldProjects {
				var isExist = false
				for _, newProject := range newProjects {
					if reflect.DeepEqual(oldProject, newProject) {
						isExist = true
						break
					}
				}
				if !isExist {
					handler.Close(&oldProject)
				}
			}

			for _, newProject := range newProjects {
				var isExist = false
				for _, oldProject := range oldProjects {
					if reflect.DeepEqual(oldProject, newProject) {
						isExist = true
						break
					}
				}
				if !isExist {
					handler.Handle(&newProject)
				}
			}
		}
	}
}
